<?php
declare (strict_types = 1);
namespace app\admin\controller;

use think\Request;
use think\facade\View;
use think\exception\ValidateException;

use app\admin\validate\GoodsValidate;
use app\admin\validate\GoodsGroupValidate;

use app\admin\model\{Cate, Admin, Goods, GoodsImg, GoodsGroup};

class GoodsController extends BaseController
{
    // 渲染商品列表页面
    public function goods_list()
    {   
        return view();
    }

    // 渲染商品添加页面
    public function goods_add()
    {   
        $adminModel = new Admin();
        $cateModel = new Cate();

        $shopList = $adminModel->getList(['role_id' => 2, 'del_time' => 0], 0);

        View::assign('shop_list', $shopList['data']);
        return view();
    }

    // 渲染商品编辑页面
    public function goods_edit()
    {   
        $data = input('get.');
        $cateModel = new Cate();
        $adminModel = new Admin();
        $goodsModel = new Goods();
        $goodsImgModel = new GoodsImg();

        $goodsInfo = $goodsModel->getFind(['id' => $data['id']])['data'];
        $goodsInfo['admin_name'] = $adminModel->getVal(['id' => $goodsInfo['admin_id']], 'nickname')['data'];

        $goodsInfo['banner_img'] = $goodsImgModel->getList(['goods_id' => $goodsInfo['id'], 'type' => 1, 'goods_type' => 1], 0)['data'];
        $goodsInfo['show_img'] = $goodsImgModel->getList(['goods_id' => $goodsInfo['id'], 'type' => 2, 'goods_type' => 1], 0)['data'];

        $shopList = $adminModel->getList([['id', '<>', $goodsInfo->getData('admin_id')], ['role_id', '=', 2], ['del_time', '=', 0]], 0);
        $cate_list = $cateModel->getList(['type' => $goodsInfo->getData('type')], 0);

        View::assign('goods', $goodsInfo);
        View::assign('shop_list', $shopList['data']);
        View::assign('cate_list', $cate_list['data']);
        return view();
    }

    /** 分类列表 */
    public function cate_list()
    {
        $data = input('');

        $cateModel = new Cate();

        $cate_list = $cateModel->getList(['type' => $data['type']], 0);

        if($cate_list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        $this->success_back('ok', $cate_list['data']);
    }

    // 获取商品列表
    public function goods_data()
    {
        $data = input('get.');

        // 验证数据
        try{
            validate(GoodsValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $cateModel = new Cate();
        $goodsModel = new Goods();
        $adminModel = new Admin();

        $where[] = ['type', 'in', [1,2,4]];
        $where[] = ['del_time', '=', 0];

        // 搜索条件
        if($data && isset($data['key'])){
            if(!empty($data['key']['title'])){
                $where[] = ['title', 'like', '%' . $data['key']['title'] . '%'];
            }
        }

        $count = $goodsModel->getNum($where)['data'];

        $field = 'id, admin_id, cate_id, small_img, title, price, status, sell_number, type, create_time';
        $list = $goodsModel->getList($where, 1, $data['page'], $data['limit'], $field, 'sell_number DESC, id DESC');

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        foreach($list['data'] as $k => $v){
            $v['admin_name'] = $adminModel->getVal(['id' => $v['admin_id']], 'nickname')['data'];
        }

        $this->success_back('ok', $list['data'], $count);
    }

    // 上架||下架
    public function setIsStatus()
    {
        $id = input('post.id');
        $goodsModel = new Goods();
        $flag = $goodsModel->setIsStatus($id);

        $this->success_back($flag['msg']);
    }

    // 商品添加
    public function goodsAdd()
    {   
        $goodsModel = new Goods();
        $goodsImgModel = new GoodsImg();
        $data = input('post.');
        
        $data['small_img'] = request()->file('small_img');

        // 验证数据
        try{
            validate(GoodsValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $goodsImgBanner = json_decode($data['banner_img'], true);
        $goodsImgShow = json_decode($data['show_img'], true);
        unset($data['banner_img']);
        unset($data['show_img']);

        if(empty($goodsImgBanner)){
            $this->error_back('轮播图不能为空');
        }

        /** 添加商品 */
        $data['small_img'] = fileUp($data['small_img'], 'goods');
        $flag = $goodsModel->add($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        /** 轮播图 */
        $goodsImg = [];
        foreach($goodsImgBanner as $key => $val){
            $bannerImgArr = [
                'img'      => $val['url'],
                'type'     => 1,
                'goods_id' => $flag['data'],
                'sort'     => $val['sort'],
            ];
            
            $goodsImg[] = $bannerImgArr;
        }

        /** 详情图 */
        foreach($goodsImgShow as $k => $v){
            $showImgArr = [
                'img'      => $v['url'],
                'type'     => 2,
                'goods_id' => $flag['data'],
                'sort'     => $val['sort'],
            ];
            
            $goodsImg[] = $showImgArr;
        }

        /** 添加图片 */
        $goodsImgModel->addAll($goodsImg);
        $this->success_back('添加成功');
    }

    // 多文件上传
    public function imgUpMany(){
        $file = request()->file('file');

        $imgUrl = fileUp($file, 'goods');
        $this->success_back('ok', $imgUrl);
    }

    // 商品信息修改
    public function goods_edit_data()
    {   
        $goodsModel = new Goods();
        $goodsImgModel = new GoodsImg();
        $data = input('post.');
        
        $data['small_img'] = request()->file('small_img');

        if($data['small_img']){
            $field = 'edit_img';
        }else{
            $field = 'edit';
        }

        // 验证数据
        try{
            validate(GoodsValidate::class)->scene($field)->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $goodsImgBanner = json_decode($data['banner_img'], true);
        $goodsImgShow = json_decode($data['show_img'], true);
        unset($data['banner_img']);
        unset($data['show_img']);

        if(empty($goodsImgBanner)){
            $this->error_back('轮播图不能为空');
        }

        /** 修改商品 */
        if($data['small_img']){
            $data['small_img'] = fileUp($data['small_img'], 'goods');
        }else{
            unset($data['small_img']);
        }

        $flag = $goodsModel->edit($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        /** 轮播图 */
        $goodsImg = [];
        foreach($goodsImgBanner as $key => $val){
            $bannerImgArr = [
                'img'      => $val['url'],
                'type'     => 1,
                'goods_id' => $data['id'],
                'sort'     => $val['sort'],
            ];
            
            $goodsImg[] = $bannerImgArr;
        }

        /** 详情图 */
        foreach($goodsImgShow as $k => $v){
            $showImgArr = [
                'img'      => $v['url'],
                'type'     => 2,
                'goods_id' => $data['id'],
                'sort'     => $val['sort'],
            ];
            
            $goodsImg[] = $showImgArr;
        }

        $goodsImgModel->del(['goods_id' => $data['id']]);

        /** 添加图片 */
        $goodsImgModel->addAll($goodsImg);
        $this->success_back('编辑成功');
    }

    // 删除商品
    public function goodsDel()
    {
        $goodsModel = new Goods();
        $data = input('post.');

        // 验证数据
        try{
            validate(GoodsValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $goodsModel->edit(['id' => $data['id'], 'del_time' => time()]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('删除成功');
    }




    // 渲染团购商品列表页面
    public function goods_group_list()
    {   
        return view();
    }

    // 渲染团购商品添加页面
    public function goods_group_add()
    {   
        $adminModel = new Admin();
        $shop_list  = $adminModel->getList(['role_id' => 2, 'del_time' => 0], 0);
        
        View::assign('shop_list', $shop_list['data']);
        return view();
    }

    /** 查询店铺的商品 */
    public function getAdminGoodsList(){
        $data = input('');

        // 验证数据
        try{
            validate(GoodsValidate::class)->scene('goods_list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $goodsModel = new Goods();

        $where[] = ['del_time', '=', 0];
        $where[] = ['status', '=', 1];
        $where[] = ['type', 'in', [1,3]];
        $where[] = ['admin_id', '=', $data['admin_id']];

        $goods_list = $goodsModel->getList($where, 0, 0, 0, 'id, title');

        if($goods_list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        $this->success_back('ok', $goods_list['data']);
    }

    // 渲染团购商品编辑页面
    public function goods_group_edit()
    {   
        $data = input('');
        $groupModel = new GoodsGroup();

        $groupInfo  = $groupModel->getFind(['id' => $data['id']])['data'];

        View::assign('group', $groupInfo);
        return view();
    }

    // 获取团购商品列表
    public function goods_group_data()
    {
        $data = input('get.');

        // 验证数据
        try{
            validate(GoodsValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $adminModel = new Admin();
        $goodsModel = new Goods();
        $groupModel = new GoodsGroup();

        $where[] = ['del_time', '=', 0];

        // 搜索条件
        if($data && isset($data['key'])){
            if(!empty($data['key']['name'])){
                $goods_ids = $goodsModel->getCol([['title', 'like', '%' . $data['key']['name'] . '%']], 'id')['data'];

                $where[] = ['goods_id', 'in', $goods_ids];
            }
        }

        $count = $groupModel->getNum($where)['data'];

        $list = $groupModel->getList($where, 1, $data['page'], $data['limit']);

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        foreach($list['data'] as $k => $v){
            $v['goods_name'] = $goodsModel->getVal(['id' => $v['goods_id']], 'title')['data'];
            $v['admin_name'] = $adminModel->getVal(['id' => $v['admin_id']], 'nickname')['data'];
        }

        $this->success_back('ok', $list['data'], $count);
    }

    // 团购商品添加
    public function group_add_data()
    {   
        $data = input('post.');

        // 验证数据
        try{
            validate(GoodsGroupValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $goodsModel = new Goods();
        $groupModel = new GoodsGroup();

        $flag = $groupModel->add($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $goodsModel->edit(['id' => $data['goods_id'], 'status' => 0]);

        $this->success_back('添加成功');
    }

    // 团购商品信息修改
    public function group_edit_data()
    {
        $data = input('post.');

        // 验证数据
        try{
            validate(GoodsGroupValidate::class)->scene('edit')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $groupModel = new GoodsGroup();

        $flag = $groupModel->edit($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('编辑成功');
    }

    // 删除团购商品
    public function group_del()
    {
        $data = input('post.');

        // 验证数据
        try{
            validate(GoodsValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $goodsModel = new Goods();
        $groupModel = new GoodsGroup();

        $flag = $groupModel->edit(['id' => $data['id'], 'del_time' => time()]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $group_info = $groupModel->getFind(['id' => $data['id']])['data'];

        $goodsModel->edit(['id' => $group_info['goods_id'], 'status' => 1]);

        $this->success_back('删除成功');
    }
    
    /** 商品图片删除 */
    public function del_imgs(){
        $data = input("post.url_img");

        $imgModel = new GoodsImg();
        $res = $imgModel->where("id", $data)->delete();

        if(!$res){
            $this->error_back('删除失败');
        }else{
            $this->success_back('删除成功');
        }
    }
}
